import React from 'react'
import { View, TextInput, TouchableOpacity } from 'react-native'
import { Controller, useFieldArray } from 'react-hook-form'
import { Icon, Text } from '@rneui/themed'
import { Picker } from '@react-native-picker/picker'
import DateTimePicker from '@react-native-community/datetimepicker'
import { leaveStyles } from '../../../styles/leaveStyles'
import { useLeaveDict } from '../../../hooks/useDict'
import { DICT_TYPE } from '../../../api/dict'

interface PersonalFormProps {
    control: any
    watch: any
    startDate: string
    endDate: string
    showDatePickers: { [key: string]: boolean }
    setShowDatePickers: (value: { [key: string]: boolean } | ((prev: { [key: string]: boolean }) => { [key: string]: boolean })) => void
    isEditMode?: boolean
    onMarkForDeletion?: (itemId: string) => void
    getValues?: any
}

export const PersonalForm: React.FC<PersonalFormProps> = ({
    control,
    watch,
    startDate,
    endDate,
    showDatePickers,
    setShowDatePickers,
    isEditMode = false,
    onMarkForDeletion,
    getValues
}) => {
    const personalArray = useFieldArray({ control, name: "personalItems" })
    const { getDictOptions } = useLeaveDict()

    return (
        <View style={leaveStyles.reasonFormContainer}>
            {personalArray.fields.map((field, index) => (
                <View key={field.id} style={leaveStyles.itemContainer}>
                    <Text style={leaveStyles.subLabel}>请假类型</Text>
                    <View style={leaveStyles.pickerContainer}>
                        <Controller
                            control={control}
                            name={`personalItems.${index}.type`}
                            render={({ field: { onChange, value } }) => (
                                <Picker
                                    selectedValue={value}
                                    onValueChange={onChange}
                                    style={leaveStyles.picker}
                                >
                                    <Picker.Item label="请选择请假类型..." value="" />
                                    {getDictOptions(DICT_TYPE.PERSONAL_TYPE).map((option, idx) => (
                                        <Picker.Item
                                            key={idx}
                                            label={option.label}
                                            value={option.value}
                                        />
                                    ))}
                                </Picker>
                            )}
                        />
                    </View>

                    <Text style={leaveStyles.subLabel}>开始时间</Text>
                    <Controller
                        control={control}
                        name={`personalItems.${index}.startDate`}
                        render={({ field: { onChange, value } }) => (
                            <View>
                                <TouchableOpacity
                                    style={leaveStyles.dateButton}
                                    onPress={() => {
                                        setShowDatePickers((prev: { [key: string]: boolean }) => ({ ...prev, [`personal_start_${index}`]: true }))
                                    }}
                                >
                                    <Text style={leaveStyles.dateButtonText}>
                                        {value || '请选择开始时间'}
                                    </Text>
                                </TouchableOpacity>
                                {showDatePickers[`personal_start_${index}`] && (
                                    <DateTimePicker
                                        value={value ? new Date(value) : new Date()}
                                        mode="date"
                                        display="default"
                                        minimumDate={startDate ? new Date(startDate) : new Date()}
                                        maximumDate={endDate ? new Date(endDate) : undefined}
                                        onChange={(event, selectedDate) => {
                                            setShowDatePickers((prev: { [key: string]: boolean }) => ({ ...prev, [`personal_start_${index}`]: false }))
                                            if (selectedDate) {
                                                onChange(selectedDate.toISOString().split('T')[0])
                                            }
                                        }}
                                    />
                                )}
                            </View>
                        )}
                    />

                    <Text style={leaveStyles.subLabel}>结束时间</Text>
                    <Controller
                        control={control}
                        name={`personalItems.${index}.endDate`}
                        render={({ field: { onChange, value } }) => (
                            <View>
                                <TouchableOpacity
                                    style={leaveStyles.dateButton}
                                    onPress={() => {
                                        setShowDatePickers((prev: { [key: string]: boolean }) => ({ ...prev, [`personal_end_${index}`]: true }))
                                    }}
                                >
                                    <Text style={leaveStyles.dateButtonText}>
                                        {value || '请选择结束时间'}
                                    </Text>
                                </TouchableOpacity>
                                {showDatePickers[`personal_end_${index}`] && (
                                    <DateTimePicker
                                        value={value ? new Date(value) : new Date()}
                                        mode="date"
                                        display="default"
                                        minimumDate={startDate ? new Date(startDate) : new Date()}
                                        maximumDate={endDate ? new Date(endDate) : undefined}
                                        onChange={(event, selectedDate) => {
                                            setShowDatePickers((prev: { [key: string]: boolean }) => ({ ...prev, [`personal_end_${index}`]: false }))
                                            if (selectedDate) {
                                                onChange(selectedDate.toISOString().split('T')[0])
                                            }
                                        }}
                                    />
                                )}
                            </View>
                        )}
                    />

                    <Text style={leaveStyles.subLabel}>总计天数</Text>
                    <View style={leaveStyles.totalDaysContainer}>
                        <Text style={leaveStyles.totalDaysText}>
                            {(() => {
                                const start = watch(`personalItems.${index}.startDate`)
                                const end = watch(`personalItems.${index}.endDate`)
                                if (start && end) {
                                    const startDate = new Date(start)
                                    const endDate = new Date(end)
                                    const diffTime = Math.abs(endDate.getTime() - startDate.getTime())
                                    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1
                                    return `${diffDays} 天`
                                }
                                return '请先选择开始和结束时间'
                            })()}
                        </Text>
                    </View>
                    
                    <Text style={leaveStyles.subLabel}>请假详情</Text>
                    <Controller
                        control={control}
                        name={`personalItems.${index}.details`}
                        render={({ field: { onChange, value } }) => (
                            <TextInput
                                style={leaveStyles.textArea}
                                value={value}
                                onChangeText={onChange}
                                placeholder="请输入请假详情"
                                multiline={true}
                                numberOfLines={2}
                                textAlignVertical="top"
                            />
                        )}
                    />

                    <Text style={leaveStyles.subLabel}>联系电话</Text>
                    <Controller
                        control={control}
                        name={`personalItems.${index}.phone`}
                        render={({ field: { onChange, value } }) => (
                            <TextInput
                                style={leaveStyles.textInput}
                                value={value}
                                onChangeText={onChange}
                                placeholder="请输入联系电话"
                                keyboardType="phone-pad"
                            />
                        )}
                    />

                    {/* 探亲假额外字段 */}
                    {(() => {
                        const currentType = watch(`personalItems.${index}.type`)
                        
                        // 获取探亲假的字典值
                        const personalTypeOptions = getDictOptions(DICT_TYPE.PERSONAL_TYPE)
                        const visitTypeOption = personalTypeOptions.find(opt => opt.label === '探亲假')
                        const isVisitType = currentType === (visitTypeOption?.value || '探亲假')
                        
                        return isVisitType && (
                            <>
                                <Text style={leaveStyles.subLabel}>探亲路线</Text>
                                <Controller
                                    control={control}
                                    name={`personalItems.${index}.route`}
                                    render={({ field: { onChange, value } }) => (
                                        <TextInput
                                            style={leaveStyles.textArea}
                                            value={value}
                                            onChangeText={onChange}
                                            placeholder="请输入探亲路线"
                                            multiline={true}
                                            numberOfLines={2}
                                            textAlignVertical="top"
                                        />
                                    )}
                                />

                                <Text style={leaveStyles.subLabel}>与探望人关系</Text>
                                <Controller
                                    control={control}
                                    name={`personalItems.${index}.relation`}
                                    render={({ field: { onChange, value } }) => (
                                        <TextInput
                                            style={leaveStyles.textInput}
                                            value={value}
                                            onChangeText={onChange}
                                            placeholder="请输入与探望人关系"
                                        />
                                    )}
                                />

                                <Text style={leaveStyles.subLabel}>被探望人姓名</Text>
                                <Controller
                                    control={control}
                                    name={`personalItems.${index}.visitName`}
                                    render={({ field: { onChange, value } }) => (
                                        <TextInput
                                            style={leaveStyles.textInput}
                                            value={value}
                                            onChangeText={onChange}
                                            placeholder="请输入被探望人姓名"
                                        />
                                    )}
                                />

                                <Text style={leaveStyles.subLabel}>探亲类别</Text>
                                <Controller
                                    control={control}
                                    name={`personalItems.${index}.visitType`}
                                    render={({ field: { onChange, value } }) => (
                                        <Picker
                                            selectedValue={value}
                                            onValueChange={onChange}
                                            mode="dropdown"
                                            style={leaveStyles.picker}
                                        >
                                            <Picker.Item label="请选择探亲类别..." value="" />
                                            {getDictOptions(DICT_TYPE.PERSONAL_VISIT_TYPE).map((option, idx) => (
                                                <Picker.Item
                                                    key={idx}
                                                    label={option.label}
                                                    value={option.value}
                                                />
                                            ))}
                                        </Picker>
                                    )}
                                />

                                <Text style={leaveStyles.subLabel}>户口所在地或地址</Text>
                                <Controller
                                    control={control}
                                    name={`personalItems.${index}.visitAddress`}
                                    render={({ field: { onChange, value } }) => (
                                        <TextInput
                                            style={leaveStyles.textArea}
                                            value={value}
                                            onChangeText={onChange}
                                            placeholder="请输入户口所在地或地址"
                                            multiline={true}
                                            numberOfLines={2}
                                            textAlignVertical="top"
                                        />
                                    )}
                                />

                                <Text style={leaveStyles.subLabel}>婚姻状况</Text>
                                <Controller
                                    control={control}
                                    name={`personalItems.${index}.maritalStatus`}
                                    render={({ field: { onChange, value } }) => (
                                        <Picker
                                            selectedValue={value}
                                            onValueChange={onChange}
                                            mode="dropdown"
                                            style={leaveStyles.picker}
                                        >
                                            <Picker.Item label="请选择婚姻状况..." value="" />
                                            {getDictOptions(DICT_TYPE.MARITAL_STATUS).map((option, idx) => (
                                                <Picker.Item
                                                    key={idx}
                                                    label={option.label}
                                                    value={option.value}
                                                />
                                            ))}
                                        </Picker>
                                    )}
                                />
                            </>
                        )
                    })()}

                    {/* 产假额外字段 */}
                    {(() => {
                        const currentType = watch(`personalItems.${index}.type`)
                        // 获取产假的字典值
                        const personalTypeOptions = getDictOptions(DICT_TYPE.PERSONAL_TYPE)
                        const maternityTypeOption = personalTypeOptions.find(opt => opt.label === '产假')
                        const isMaternityType = currentType === (maternityTypeOption?.value || '产假')
                        
                        return isMaternityType && (
                            <>
                                <Text style={leaveStyles.subLabel}>生育次数</Text>
                                <Controller
                                    control={control}
                                    name={`personalItems.${index}.parity`}
                                    render={({ field: { onChange, value } }) => (
                                        <Picker
                                            selectedValue={value}
                                            onValueChange={onChange}
                                            mode="dropdown"
                                            style={leaveStyles.picker}
                                        >
                                            <Picker.Item label="请选择生育次数..." value="" />
                                            {getDictOptions(DICT_TYPE.PARITY).map((option, idx) => (
                                                <Picker.Item
                                                    key={idx}
                                                    label={option.label}
                                                    value={option.value}
                                                />
                                            ))}
                                        </Picker>
                                    )}
                                />

                                <Text style={leaveStyles.subLabel}>是否多胞胎</Text>
                                <Controller
                                    control={control}
                                    name={`personalItems.${index}.multiple`}
                                    render={({ field: { onChange, value } }) => (
                                        <Picker
                                            selectedValue={value}
                                            onValueChange={onChange}
                                            mode="dropdown"
                                            style={leaveStyles.picker}
                                        >
                                            <Picker.Item label="请选择是否多胞胎" value="" />
                                            {getDictOptions(DICT_TYPE.IS_PRESENTATION).map((option, idx) => (
                                                <Picker.Item
                                                    key={idx}
                                                    label={option.label}
                                                    value={option.value}
                                                />
                                            ))}
                                        </Picker>
                                    )}
                                />

                                <Text style={leaveStyles.subLabel}>是否难产</Text>
                                <Controller
                                    control={control}
                                    name={`personalItems.${index}.dystocia`}
                                    render={({ field: { onChange, value } }) => (
                                        <Picker
                                            selectedValue={value}
                                            onValueChange={onChange}
                                            mode="dropdown"
                                            style={leaveStyles.picker}
                                        >
                                            <Picker.Item label="请选择是否难产" value="" />
                                            {getDictOptions(DICT_TYPE.IS_PRESENTATION).map((option, idx) => (
                                                <Picker.Item
                                                    key={idx}
                                                    label={option.label}
                                                    value={option.value}
                                                />
                                            ))}
                                        </Picker>
                                    )}
                                />
                            </>
                        )
                    })()}

                    {personalArray.fields.length > 1 && (
                        <View style={leaveStyles.deleteButtonContainer}>
                            <Icon
                                name="close"
                                type="material"
                                size={20}
                                color="white"
                                containerStyle={leaveStyles.circularDeleteButton}
                                onPress={() => {
                                    if (isEditMode && onMarkForDeletion) {
                                        const currentFormData = getValues()
                                        const realId = currentFormData.personalItems?.[index]?.id
                                        if (realId && typeof realId === 'number') {
                                            onMarkForDeletion(realId.toString())
                                        }
                                        personalArray.remove(index)
                                    } else {
                                        personalArray.remove(index)
                                    }
                                }}
                            />
                        </View>
                    )}
                </View>
            ))}
            <View style={leaveStyles.addButtonContainer}>
                <TouchableOpacity
                    style={leaveStyles.circularAddButton}
                    onPress={() => personalArray.append({
                        startDate: startDate || "",
                        endDate: endDate || "",
                        type: "",
                        details: "",
                        phone: "",
                        route: "",
                        relation: "",
                        visitName: "",
                        visitType: "",
                        visitAddress: "",
                        maritalStatus: "",
                        parity: "",
                        multiple: "",
                        dystocia: ""
                    })}
                >
                    <Icon
                        name="add"
                        type="material"
                        size={20}
                        color="white"
                    />
                </TouchableOpacity>
            </View>
        </View>
    )
}
